/* $Id: ProblemsModel.java 129 2011-08-26 05:27:43Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models;

import java.util.List;
import java.util.HashMap;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.ProblemEntry;


public class ProblemsModel
{
	private static CoreInterface<ProblemEntry> core = Deployment.isGAE() ?
		new AbstractBigtableModelCore<ProblemEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("sid");
			}
			
			@Override
			protected Class<ProblemEntry> getEntryClass()
			{
				return ProblemEntry.class;
			}
		}
	:
		new AbstractDBModelCore<ProblemEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("sid");
			}
			
			@Override
			protected Class<ProblemEntry> getEntryClass()
			{
				return ProblemEntry.class;
			}
		};		
	
	public static List<ProblemEntry> getAllEntries()
	{
		return core.getAllEntries();
	}

	public static ProblemEntry getEntry(Long problemId)
	{
		return core.getEntry(problemId);
	}
	
	public static boolean deleteEntry(Long problemId)
	{
		return core.deleteEntry(problemId);
	}
	
	public static HashMap<Long, ProblemEntry> getEntriesMap()
	{
		List<ProblemEntry> list = getAllEntries();
		HashMap<Long, ProblemEntry> result = new HashMap<Long, ProblemEntry>();
		for (ProblemEntry entry: list)
			result.put(entry.getId(), entry);
		return result;
	}

	public static void addBatch(String sidPrefix, String sid1, String sidn,
			String timeLimit, String memoryLimit, String djudgeContest,
			Boolean active)
	{
		Integer tl = Integer.parseInt(timeLimit);
		Integer ml = Integer.parseInt(memoryLimit);
		for (char c = sid1.charAt(0); c <= sidn.charAt(0); c++)
		{
			ProblemEntry pe = new ProblemEntry();
			pe.setActive(active);
			pe.setDjudgeContest(djudgeContest);
			pe.setDjudgeProblem("" + c);
			pe.setMemoryLimit(ml);
			pe.setTimeLimit(tl);
			pe.setName("Problem " + c);
			pe.setSid(sidPrefix + "-" + c);
			pe.setStatement("<h1>Empty</h1>");
			pe.makePersistent();
		}
	}
	
	public static CoreInterface<ProblemEntry> getCore()
	{
		return core.getAdapter();
	}	
}
